package com.jike.shop.cloud.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.springframework.messaging.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Component;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Component
@Slf4j
public class RocketMQProducer {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    // 消息发送方法
    public void sendMessage(String topic, String msg){
        this.rocketMQTemplate.convertAndSend(topic, msg);
    }

    public void sendMessageInTransaction(String topic, String tag, String msg){
        Message message = MessageBuilder.withPayload(msg).build();
        String destination = StringUtils.isEmpty(tag) ? topic : topic + ":" + tag;
        TransactionSendResult result= rocketMQTemplate.sendMessageInTransaction(destination, message, null);
        String sendStatus = result.getSendStatus().name();
        // 本地事务执行状态
        String localTxState = result.getLocalTransactionState().name();
        log.info("send tx message sendStatus:{},localTXState:{}",sendStatus,localTxState);
        log.info("发送消息成功");
    }



}
